package com.example.mydy;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.mydy.model.Task;
import com.example.mydy.model.UserInfo;
import com.example.mydy.utils.ImageUtils;
import com.example.mydy.utils.MockDataManager;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

public class SubmitTaskActivity extends AppCompatActivity {

    private static final String TAG = "SubmitTaskActivity";
    private static final int REQUEST_PERMISSION_CODE = 1001;

    private EditText taskTitleEditText;
    private EditText taskDescriptionEditText;
    private Button submitButton;
    private Button selectImageButton;
    private ImageButton backButton;
    private TextView imageNameTextView;
    private ImageView taskImageView;

    private MockDataManager mockDataManager;
    private UserInfo currentUser;
    
    private Uri selectedImageUri;
    private byte[] imageData;

    // 使用新的Activity Result API
    private final ActivityResultLauncher<Intent> imagePickerLauncher = 
        registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), 
            result -> {
                if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                    handleImageResult(result.getData());
                }
            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submit_task);

        // 初始化数据管理器
        mockDataManager = MockDataManager.getInstance();
        currentUser = mockDataManager.getCurrentUser();

        if (currentUser == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 初始化视图
        initViews();
        setupListeners();
    }

    private void initViews() {
        taskTitleEditText = findViewById(R.id.task_title);
        taskDescriptionEditText = findViewById(R.id.task_description);
        submitButton = findViewById(R.id.btn_submit);
        backButton = findViewById(R.id.btn_back);
        selectImageButton = findViewById(R.id.btn_select_image);
        imageNameTextView = findViewById(R.id.tv_image_name);
        taskImageView = findViewById(R.id.iv_task_image);
    }

    private void setupListeners() {
        backButton.setOnClickListener(v -> finish());

        selectImageButton.setOnClickListener(v -> checkPermissionAndOpenGallery());

        submitButton.setOnClickListener(v -> {
            if (validateInput()) {
                showConfirmDialog();
            }
        });
    }

    private void checkPermissionAndOpenGallery() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) 
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, 
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 
                    REQUEST_PERMISSION_CODE);
        } else {
            openGallery();
        }
    }

    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        imagePickerLauncher.launch(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, 
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openGallery();
            } else {
                Toast.makeText(this, "需要存储权限才能选择图片", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void handleImageResult(Intent data) {
        selectedImageUri = data.getData();
        if (selectedImageUri != null) {
            try {
                // 显示文件名
                String imageName = ImageUtils.getFileNameFromUri(this, selectedImageUri);
                imageNameTextView.setText(imageName);
                
                // 读取图片数据
                InputStream is = getContentResolver().openInputStream(selectedImageUri);
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                is.close();
                
                // 压缩图片
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);
                imageData = baos.toByteArray();
                
                // 显示预览
                taskImageView.setImageBitmap(bitmap);
                taskImageView.setVisibility(View.VISIBLE);
                
            } catch (IOException e) {
                Log.e(TAG, "Error handling image: " + e.getMessage());
                Toast.makeText(this, "读取图片失败", Toast.LENGTH_SHORT).show();
                imageNameTextView.setText("未选择图片");
                taskImageView.setVisibility(View.GONE);
                selectedImageUri = null;
                imageData = null;
            }
        }
    }

    private boolean validateInput() {
        String title = taskTitleEditText.getText().toString().trim();
        String description = taskDescriptionEditText.getText().toString().trim();

        if (title.isEmpty()) {
            taskTitleEditText.setError("请输入任务标题");
            return false;
        }

        if (description.isEmpty()) {
            taskDescriptionEditText.setError("请输入任务描述");
            return false;
        }

        if (selectedImageUri == null || imageData == null) {
            Toast.makeText(this, "请选择任务证明图片", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    private void showConfirmDialog() {
        String title = taskTitleEditText.getText().toString().trim();

        new AlertDialog.Builder(this)
                .setTitle("确认提交")
                .setMessage("您确定要提交以下任务吗？\n\n任务标题：" + title + 
                        "\n任务描述：" + taskDescriptionEditText.getText().toString())
                .setPositiveButton("确认提交", (dialog, which) -> {
                    submitTask(title, taskDescriptionEditText.getText().toString());
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void submitTask(String title, String description) {
        // 在实际应用中，这里应该调用网络API提交任务
        // 在本例中，我们使用模拟数据进行演示
        
        // 创建待审核任务
        Task task = new Task();
        task.setTitle(title);
        task.setDescription(description);
        task.setStatus(Task.STATUS_PENDING);
        task.setUsername(currentUser.getUsername());
        task.setSubmittedAt(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        
        // 保存图片数据
        String imageUrl = ImageUtils.saveImageToInternalStorage(this, imageData, "task_" + System.currentTimeMillis());
        task.setImageUrl(imageUrl);
        
        boolean success = mockDataManager.submitTask(task);
        
        if (success) {
            // 显示简短的成功提示
            Toast.makeText(this, "任务提交成功", Toast.LENGTH_SHORT).show();
            
            // 返回上一个Activity (MyTasksActivity)，并传递新任务的ID用于高亮显示
            Intent resultIntent = new Intent();
            resultIntent.putExtra("taskId", (long)task.getId());
            setResult(RESULT_OK, resultIntent);
            finish(); // 结束当前页面
        } else {
            Toast.makeText(this, "任务提交失败，请稍后重试", Toast.LENGTH_SHORT).show();
        }
    }
} 